<template>
    <div class="container" style="padding: 0;margin: 0; ">
        <div class="flex-col full">
            <div class="w_full flex-row-center " style="margin-top: 16px;">
                <div class="title">编辑</div>
                <el-button style="margin-left:16px;" link class="back_title" @click="click_back" :icon="Back">返回资料库</el-button>

            </div>

            <div class="flex_1 flex-row comm_border" style="margin-top: 16px;">
                <div class="flex-col" style="margin: 24px;">
                    <div class="flex-row">
                        <div class="user_title_rec"></div>
                        <div class="user_title">基本信息</div>
                    </div>
                    <div class="user_content" style="margin-top: 12px;margin-left: 50px;">
                        <el-form label-position="left"
                                 :model="data" label-width="100px"
                                 ref="form"
                                 style="margin: 10px; width: auto">
                            <el-form-item class="form_item" prop="qtType" label="*资料名称">
                                <div>{{ data.dataBank.dataName }}</div>
                            </el-form-item>
                            <el-form-item class="form_item" prop="qtType" label="标签分类">
                                <div>{{ data.dataBank.tagId }}</div>
                            </el-form-item>
                            <el-form-item class="form_item" prop="qtType" label="描述">
                                <div>{{ data.dataBank.dataDesc }}</div>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="flex-row">
                        <div class="user_title_rec"></div>
                        <div class="user_title">上传附件</div>
                    </div>
                    <div class="user_content" style="margin-top: 12px; margin-left: 50px;">
                        <el-form label-position="left"
                                 :model="data" label-width="100px"
                                 ref="form"
                                 style="margin: 10px; width: auto">
                            <el-form-item class="form_item" prop="qtType" label="上传附件">
                                <div class="flex-col">
                                    <el-upload action="#"
                                               ref="uploadrefss"
                                               limit="1"
                                               :multiple="false"
                                               :show-file-list="true"
                                               :http-request="uploadHttpRequest"
                                               :file-list="data.fileList">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                    </el-upload>


                                </div>
                            </el-form-item>
                            <el-form-item class="form_item" prop="qtType" label="附件列表">
                                <el-table :data="data.dataBankFiles" border>
                                    <el-table-column prop="index" label="序号" width="60" />
                                    <el-table-column prop="fileName" label="文件名称" width="400" />


                                    <el-table-column label="操作" width="120px">
                                        <template #default="scope">
                                            <el-button link size="small" @click="click_download(scope.$index, scope.row)">
                                                下载
                                            </el-button>
                                            <!--                      <a :href="scope.row.filePath">下载文件</a>-->
                                            <el-button link size="small" type="danger" @click="click_delete(scope.$index, scope.row)">
                                                删除
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>
                        </el-form>

                        <el-pagination v-model:current-page="pager.currentPage"
                                       v-model:page-size="pager.pageSize"
                                       :page-sizes="[10,20,30,50]"
                                       layout="->,total, sizes, prev, pager, next, jumper"
                                       :total="pager.total"
                                       @size-change="handleSizeChange"
                                       @current-change="handleCurrentChange" />
                    </div>

                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { onMounted, reactive, ref } from "vue";
    import { useRoute } from "vue-router";
    import router from "@/router";
    import msg from "@/components/msg";
    import { api_deleteFile, api_getFileList, api_uploadFile } from "@/request/apis/fileApi";
    import { api_getDataBankById } from "@/request/apis/dataBankApi";
    import { DataBankInfoVO } from "@/type/vo/DataBankInfoVO";
    import { ElNotification, UploadInstance, UploadRequestOptions } from "element-plus";
    import { AttachmentInfoVO } from "@/type/vo/AttachmentInfoVO";
    import { tickAsTimeString } from "@/utils/TimeUtil";
    import axios from "axios";
    import {Back} from "@element-plus/icons-vue";


    const route = useRoute();
    const dataId = route.query.dataId as string;

    const data = reactive({
        dataBank: {} as DataBankInfoVO,
        dataBankFiles: Array<AttachmentInfoVO>(),
        fileList: [],
    })
    const pager = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 10,
    })
    onMounted(async () => {
        pager.currentPage = 1;
        pager.pageSize = 10;
        await search_pri();
        await search_File();
    })
    const handleSizeChange = async (val: number) => {
        await search_File();
    }
    const handleCurrentChange = async (val: number) => {
        await search_File();
    }
    const search_pri = async () => {
        const limit = pager.pageSize;
        const page = pager.currentPage;
        let r = await api_getDataBankById(dataId);
        if (!r) {
            await msg.error("数据异常");
            return;
        }
        if (r.code != 0) {
            await msg.error(`数据异常!  ${r.code} msg：${r.msg}`);
            return;
        }
        data.dataBank = r.data;
    }

    const search_File = async () => {
        data.dataBankFiles.length = 0;
        const limit = pager.pageSize;
        const page = pager.currentPage;
        let r = await api_getFileList(dataId, limit, page);
        if (!r) {
            await msg.error("数据异常");
            return;
        }
        if (r.code != 0) {
            await msg.error(`数据异常!  ${r.code} msg：${r.msg}`);
            return;
        }
        if (r.data.records) {
            for (let i = 0; i < r.data.records.length; i++) {
                r.data.records[i].index = i + 1;
                r.data.records[i].fileUploadTimeStr = tickAsTimeString(r.data.records[i].fileUploadTime)
            }
        }
        data.dataBankFiles = r.data.records;
        pager.total = r.data.total;
    }

    const click_back = () => {
        router.back();
    }
    const file = ref()
    const uploadHttpRequest = async (option: UploadRequestOptions) => {
        let formData = new FormData();
        formData.append("multipartFile", option.file);
        formData.append("linkKey", dataId);
        formData.append("linkType", '1');
        formData.append("fileType", '1');
        formData.append("fileVersion", '1');
        formData.append("orderIndex", '1');

        //let uploadrefss = ref();
        //uploadrefss.clearFiles();
        let uploadrefss = ref<UploadInstance>();
        uploadrefss.value?.clearFiles();
        data.fileList = [];
        let r = await api_uploadFile(formData);
        if (!r) {
            await msg.error("数据异常");
            return;
        }
        if (r.code != 0) {
            await msg.error(`数据异常!  ${r.code} msg：${r.msg}`);
            return;
        }
        await msg.info('上传成功!');
        await search_File();
        return false;
    };

    const click_download = (index: number, row: AttachmentInfoVO) => {
        const url = row.fileId;  								// 从行数据中获取下载链接
        const name = row.fileName;  								// 从行数据中获取下载链接
        // const link = document.createElement('a')				// 创建链接标签，即a标签，并将dom命名为link
        // link.href = url											// 为dom为link的元素添加链接
        // link.setAttribute('download', '')						// 为link设置下载属性
        // document.body.appendChild(link)							// 把创建并配置好的link dom添加到页面文档中
        // link.click()											// 模拟dom的点击事件
        // document.body.removeChild(link)
        downloadFile3(url, name);// 从文档中移出link节点

    }
    const downloadFile3 = (id: string, name: string) => {
        let token = '';
        if (localStorage.getItem('token')) {
            token = `${localStorage.getItem('token')}`;
        }
        let url = 'lunaApi/file_upload?id=' + id + '&token=' + token + '&appId=assist';
        downloadFIle4(url, name);

        console.log(url);
    }


    const downloadFIle4 = (url: string, name: string) => {
        var ajax = new XMLHttpRequest();
        ajax.open("GET", url, true);
        ajax.responseType = "blob";
        //下载完流的状态
        ajax.onload = (evt) => {
            let blob = new Blob([ajax.response]);
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = name;
            link.click();
        };
        ajax.send();
    }



    const click_delete = async (index: number, row: AttachmentInfoVO) => {
        // await api_deleteFile(api_deleteFile);
        // 从文档中移出link节点
        try {
            const rDialog = await msg.yesNo(
                `是否确认删除文件 ${row.fileName}?`,
                '警告'
            );
            if (rDialog) {
                const r = await api_deleteFile(row.fileId);
                if (!r) {
                    await msg.info('数据异常');
                    return;
                }
                if (r.code != 0) {
                    await msg.info(`数据异常!  ${r.code} msg：${r.msg}`);
                    return;
                }
                await search_pri();
                ElNotification({
                    title: '提示',
                    message: '已删除!',
                })
            }
        } catch (error) {
            // 处理取消操作
        }
    }
    //click_delete

</script>

<style scoped>
    .user_image {
        width: 150px;
        height: 150px;
    }

    .selectFile {
        border-radius: 2px 2px 2px 2px;
        border: 1px solid red;
        opacity: 1;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        outline: medium none;
        cursor: pointer;
        -moz-opacity: 0;
        filter: alpha(opacity=0);
    }

    .selectFile_txt {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.6);
        line-height: 22px;
    }

    .user_userName {
        font-size: 24px;
        font-weight: 600;
        color: #0A1629;
        line-height: 28px;
        margin-top: 32px;
    }

    .user_userId {
        font-size: 16px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
        line-height: 24px;
        margin-top: 16px;
    }

    .user_title_rec {
        width: 4px;
        height: 28px;
        background: #3F8CFF;
        border-radius: 2px 2px 2px 2px;
        opacity: 1;
    }

    .user_title {
        font-size: 20px;
        font-weight: 400;
        color: #0A1629;
        line-height: 23px;
        margin-left: 8px;
    }

    .form_item {
        margin-top: 16px;
    }


    .grid-container {
        display: grid;
        grid-template-rows: auto 1fr auto;
        height: 100%;
    }

    .row {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .row-1,
    .row-3 {
    }

    .row-2 {
        overflow: auto;
    }

    .scrollable-content {
        line-height: 1.5em;
    }


    .title {
        font-size: 24px;
        font-weight: 600;
        color: #0A1629;
        line-height: 28px;
    }

    .back_title {
        font-size: 16px;
        font-weight: 600;
        color: #3F8CFF;
        line-height: 19px;
    }

    .user_data {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
        margin-left: 16px;
    }

    .date-picker {
        height: 48px;
        color: black;
        background: #FFFFFF;
        border-radius: 8px 8px 8px 8px;
        opacity: 1;
        border: 1px solid #DCDCDC;
    }

    .el-scrollbar__view {
        height: calc(100% - 100px); /* 根据实际情况调整高度 */
    }

    .infinite-list {
        padding: 0;
        margin: 0;
        list-style: none;
    }

        .infinite-list .infinite-list-item {
            display: flex;
            align-items: center;
            justify-content: center;
            background: black;
            margin: 10px;
            color: var(--el-color-primary);
            overflow: hidden;
        }

            .infinite-list .infinite-list-item + .list-item {
                margin-top: 10px;
            }

    .naireName {
        font-size: 20px;
        font-weight: 400;
        color: #0A1629;
        line-height: 24px;
    }
</style>

